<template>
	<view>
		<view class="pad-lr-30 hetop">
			<view class="pad-lr-10 mar-top-20 radius-16 my_bi_view over-hid display align-items-start">
				<view class="display-sb align-items-end width-100">
					<view class="display align-items-end">
						<view class="ml30">
							<view class="col-f fontSize-30 mar-top-30">余额（元）</view>
							<view class="col-f fontSize-32 mar-top-30 fontBold">{{num}}</view>					
						</view>
						<view class="ml60">
							<view class="col-f fontSize-30 mar-top-30">7天冻结金额</view>
							<view class="col-f fontSize-32 mar-top-30 fontBold">{{ parseFloat(unfreezeAmount).toFixed(2) }}</view>					
						</view>
					</view>
					<view class="fontSize-28 radius-30 pad-tb-10 pad-lr-38 bgfff mar-right-30" style="color: #F6911B;" @click="goWithdrawal" v-if="type==2||(is_withdraw==1&&type==1)">提现</view>
				</view>
			</view>
			<view class="mar-top-40 fontSize-32 display-sb align-items">
				<view class="display align-items">
					<view class="" :class="list_type==1?'fontBold':'fontSize-28'" @click="seemony">余额明细</view>
					<view class="ml30" :class="list_type==2?'fontBold':'fontSize-28'" @click="seeti">提现记录</view>
				</view>
				
				<view class="display align-items" @click="openshowwin">
					<image src="/static/img/icon_shaixuanshijian.png" class="proudct-item-icon-24" mode=""></image>
					<view class="ml10 fontSize-28 col-6">筛选时间</view>
				</view>
			</view>
			<view class="pad-tb-30 bordbottom display-sb align-items" v-for="item in list" :key="item.id">
				<view v-if="list_type==2" class="width-100">
					<view class="display-sb align-items">
						<view class="fontSize-32" v-if="list_type==2" >提现金额:{{item.money}}</view>
						<view class="fontSize-32" v-if="list_type==2" >到账金额:{{item.arrival_money}}</view>
						<view class="fontSize-32" v-if="list_type==2" >手续费:{{item.server_money}}</view>
					</view>
					<view class="display-sb align-items mar-top-12">
						<view class="mar-top-8 col-9 fontSize-26 display">{{item.create_time_text}} <text class="ml20">{{item.status==1?'待审核':item.status==2?'通过审核':item.status==9?'已驳回':''}}</text></view>
						<view class="fontSize-28 radius-30 pad-tb-10 pad-lr-20 col-f shou_btn" @click="goWAIT_USER(item)" v-if="item.wx_status=='WAIT_USER_CONFIRM'">确认收款</view>
					</view>
				</view>
				<view class="width-80" v-if="list_type==1">
					<view class="fontSize-28 text-clamp-2">{{item.memo}}</view>
					<view class="mar-top-8 col-9 fontSize-26">{{item.create_time_text}}</view>
				</view>
				<view v-if="list_type==1">
					<view class="fontSize-32">{{item.money}}</view>
				</view>
				
			</view>
			<view class="display-ce align-items" v-if="list.length==0">
				<tm-result :showBtn="false" subTitle=" " title="暂无数据" color="#bc8c1e"></tm-result>
			</view>
		</view>
		
		
		<tm-time-picker
					:showDetail="{
						year: true,
						month: true,
						day: false,
						hour: false,
						minute: false,
						second: false
					}"
					v-model:show="show"
					 v-model="modelvalue"
					format="YYYY-MM"
					v-model:model-str="data"
					color="#bc8c1e"
					@confirm="confirm"
				></tm-time-picker>
	</view>
</template>

<script lang="ts" setup>

import {moneyLog,shopmoneyLog,userWithdrawList,shopWithdrawList,getLinkageIncomeStats,getRegionCommissionStats,checkSpecialUnfreeze} from '@/utils/api'
import { onLoad, onUnload,onReachBottom } from '@dcloudio/uni-app';
import { ref, onMounted } from 'vue';
onLoad((p)=>{
	type.value = p.type
	num.value = p.num
	is_withdraw.value = p.is_withdraw
	_my_payments_code()
	getUnfreezeAmount() // 获取7天解冻金额
	uni.$on('upnum',(e)=>{
		num.value = e
	})
})
onReachBottom(()=>{
	if(page.value>1){
		_my_payments_code()
	}
})
onUnload(()=>{
	uni.$off('upnum')
})
const list_type = ref(1)//列表类型1-余额明细2-提现记录
const is_withdraw = ref(0)
const modelvalue = ref()
const type = ref(1)
const num = ref(0)
const data = ref()
const list = ref([])
const page = ref(1)
const show = ref(false)
const unfreezeAmount = ref('0.00') // 7天解冻金额
const hasSpecialUnfreeze = ref(false) // 特殊解冻标记

// 获取7天解冻金额（我的收益里的可用余额 + 区域冻结金额）
const getUnfreezeAmount = async () => {
	try {
		// 先获取特殊解冻标记状态
		const specialUnfreezeResponse = await checkSpecialUnfreeze({})
		if (specialUnfreezeResponse.code === 1 && specialUnfreezeResponse.data) {
			hasSpecialUnfreeze.value = specialUnfreezeResponse.data.has_special_unfreeze
		}
		
		let totalFrozenAmount = 0
		
		// 获取我的收益里的可用余额（考虑特殊解冻标记）
		const linkageResponse = await getLinkageIncomeStats({})
		if (linkageResponse.code === 1 && linkageResponse.data) {
			let availableAmount = parseFloat(linkageResponse.data.frozen_amount || '0')
			
			// 如果有特殊解冻标记，将冻结金额加回可用余额
			if (hasSpecialUnfreeze.value) {
				const frozenAmount = parseFloat(linkageResponse.data.total_income || '0') - availableAmount
				availableAmount += frozenAmount
			}
			
			totalFrozenAmount += availableAmount
		}
		
		// 获取区域代理佣金冻结金额
		const regionResponse = await getRegionCommissionStats({})
		if (regionResponse.code === 1 && regionResponse.data) {
			totalFrozenAmount += parseFloat(regionResponse.data.frozen_amount || '0')
		}
		
		unfreezeAmount.value = totalFrozenAmount.toFixed(2)
	} catch (error) {
		console.error('获取冻结金额失败:', error)
		unfreezeAmount.value = '0.00'
	}
}

const _my_payments_code =() =>{
	if(type.value==1){
		moneyLog({page:page.value,limit:10,date:data.value,type:''}).then(res=>{
			uni.hideLoading()
			if(res.code==1){
				list.value =list.value.concat(res.data.money_log.data)
				if(res.data.money_log.data.length>0){
					page.value++
				}
			}
		}).catch(error => {
			uni.hideLoading()
			console.error('获取余额明细失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		})		
	}else{
		shopmoneyLog({page:page.value,limit:10,date:data.value,type:''}).then(res=>{
			uni.hideLoading()
				if(res.code==1){
					list.value =list.value.concat(res.data.money_log.data)
					if(res.data.money_log.data.length>0){
						page.value++
					}
				}
			}).catch(error => {
				uni.hideLoading()
				console.error('获取店铺余额明细失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			})
	}
}
const seemony =()=>{
	list_type.value = 1
	page.value = 1
	list.value = []
	_my_payments_code()
}
const seeti=()=>{
	list_type.value = 2
	page.value = 1
	list.value = []
	_shopWithdrawList()
}
const _shopWithdrawList=()=>{
	if(type.value==1){
		userWithdrawList({page:page.value,limit:10,date:data.value}).then(res=>{
			if(res.code==1){
				list.value =list.value.concat(res.data.withdraw.data)
				if(res.data.withdraw.data.length>0){
					page.value++
				}
			}
		}).catch(error => {
			console.error('获取用户提现记录失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		})
	}else{
		shopWithdrawList({page:page.value,limit:10,date:data.value}).then(res=>{
			if(res.code==1){
				list.value =list.value.concat(res.data.withdraw.data)
				if(res.data.withdraw.data.length>0){
					page.value++
				}
			}
		}).catch(error => {
			console.error('获取店铺提现记录失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		})
	}
}
const _sales_index = () =>{
	page.value = 1
	list.value = []
	show.value = false
	_my_payments_code()
}

const openshowwin = () =>{
	show.value = true
}
const confirm =(e) =>{
	console.log(e)
		uni.showLoading({
			title:'加载中...'
		})
	show.value = false
	setTimeout(()=>{
		console.log(data.value,modelvalue.value)
	_sales_index()
	},1000)
}
const goWAIT_USER =(item) =>{
	if (wx.canIUse('requestMerchantTransfer')) {
	  wx.requestMerchantTransfer({
	    mchId: item.mchid,
	    appId: item.appid,
	    package: item.package,
	    success: (res) => {
	      // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
	      console.log('success:', res);
		  seeti()
	    },
	    fail: (res) => {
	      console.log('fail:', res);
	    },
	  });
	} else {
	  wx.showModal({
	    content: '你的微信版本过低，请更新至最新版本。',
	    showCancel: false,
	  });
	}
}
const goWithdrawal = () =>{
	uni.navigateTo({
		url:'/mypages/Withdrawal/Withdrawal?num='+num.value+'&type='+type.value
	})
}
</script>

<style lang="scss">
.my_bi_view{
	height: 240rpx;
	background: linear-gradient( 180deg, #F6911B 0%, #F8C44A 100%);
}
.bordbottom{
	border-bottom: 2rpx solid #F1F1F1;
}
.time_view{
	width: 270rpx;
	background: #F9F9F9;
}
.btn_qury{
	width: 600rpx;
	height: 80rpx;
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	margin: 100rpx auto 0 auto;
	line-height: 80rpx;
}
.shou_btn{
	background: linear-gradient(270deg, #bc8c1e 0%, #bc8c1e 100%);
}
.text-align-center{
	text-align: center;
}
</style>
